const API_BASE_URL = 'http://localhost:3000/api';

export interface News {
  id?: number;
  title: string;
  date: string;
  excerpt: string;
  img: string;
  created_at?: string;
}

export async function getNews() {
  const response = await fetch(`${API_BASE_URL}/news`);

  if (!response.ok) {
    throw new Error('获取新闻失败');
  }

  return response.json();
}

export async function getNewsDetail(title: string) {
  const response = await fetch(`${API_BASE_URL}/news/${encodeURIComponent(title)}`);

  if (!response.ok) {
    throw new Error('获取新闻详情失败');
  }

  return response.json();
}

export async function addNews(news: Omit<News, 'id' | 'created_at'>) {
  const response = await fetch(`${API_BASE_URL}/news`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(news),
  });
  return await response.json();
}

export async function updateNews(news: News) {
  const response = await fetch(`${API_BASE_URL}/news/${news.id}`, {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(news),
  });
  return await response.json();
}

export async function deleteNews(id: number) {
  const response = await fetch(`${API_BASE_URL}/news/${id}`, {
    method: 'DELETE'
  });
  return await response.json();
}